import {
	Button,
	Collapse,
	Form,
	Row,
	Col,
	Input,
	message,
	Cascader,
	TreeSelect,
	Steps,
	Space,
} from 'antd'
import {InfoCircleOutlined} from '@ant-design/icons'
import React, {useState, useEffect, memo} from 'react'
import {history, connect} from 'umi'
import styles from './index.less'
import {
	addStandby,
	editStandby,
	viewStandby,
	getNodeList,
} from '@/service/carMessage/standby'
import {getCompany} from '@/service/system/company'
import {translateDataToTree} from '@/utils/common/index'
import {getAllCitys} from '@/service/common'
import OperationRecord from '@/components/OperationRecord'

const {TextArea} = Input
const {Step} = Steps
const {Panel} = Collapse

const customizeHeader = (value: string) => (
	<div>
		<div className={styles.tip} />
		{value}
	</div>
)

const standbyAdd = memo((props: {user: any; location: any}) => {
	const {orgId} = props.user
	const {id} = props.location.query
	const [stepsList, setStepsList] = useState<any>([])
	const [type, setType] = useState<string>()
	const [form] = Form.useForm<any>()
	const [otherData, setOtherData] = useState<any>()

	const [standbyId, setStandbyId] = useState()
	const [orgSource, setOrgSource] = useState<any>([])
	const [citysList, setCitysList] = useState([])

	/** 获取城市列表 */
	const getCitysFun = () => {
		getAllCitys().then((res: any) => {
			if (res?.data) {
				setCitysList(() => res.data)
			}
		})
	}

	useEffect(() => {
		getCitysFun()
	}, [orgId])

	// 获取组织机构数据
	const onOrgFun = () => {
		getCompany({merchantId: orgId}).then((res: any) => {
			if (res?.success) {
				const list: any = translateDataToTree(res?.data)
				setOrgSource(list as any)
			}
		})
	}

	useEffect(() => {
		onOrgFun()
	}, [orgId])

	// 流程节点变化
	const onStepsChange = (value: number) => {
		const list = [...stepsList]
		if (list[value].nodeTurn === 0) {
			list[value].nodeTurn = 1
		} else {
			list[value].nodeTurn = 0
		}
		setStepsList(list)
	}

	// 初始化-详情数据
	const getView = (ids: string) => {
		viewStandby({id: ids}).then((res: any) => {
			if (res?.success) {
				const list = res?.data?.nodeList?.map(
					(
						item: {
							nodeName: string
							nodeTurn?: number
							nodeSort?: number
							nodeId: number
						},
						index: number,
					) => ({
						nodeSort: index,
						nodeId: item.nodeId,
						nodeName: item.nodeName,
						nodeTurn: item.nodeTurn,
					}),
				)
				setStepsList(() => [...list])
				form.setFieldsValue({
					...res.data,
					nodeList: [...list],
					city: [res?.data?.parentCityId, res?.data?.cityId],
				})

				setOtherData({
					...otherData,
					companyName: res?.data?.companyName,
					parentCityId: res?.data?.parentCityId,
					cityId: res?.data?.cityId,
					cityName: res?.data?.cityName,
				})
			}
		})
	}
	// 获取流程列表
	const nodeList = () => {
		getNodeList().then((res: any) => {
			if (res?.success) {
				const list = res?.data?.map(
					(
						item: {
							nodeName: string
							nodeTurn?: number
							nodeSort?: number
							nodeId: number
						},
						index: number,
					) => {
						if (index === 0 || index === res.data.length - 1) {
							return {
								nodeSort: index,
								nodeId: item.nodeId,
								nodeName: item.nodeName,
								nodeTurn: 0,
							}
						}
						return {
							nodeSort: index,
							nodeId: item.nodeId,
							nodeName: item.nodeName,
							nodeTurn: 1,
						}
					},
				)
				setStepsList(() => [...list])
				form.setFieldsValue({
					nodeList: [...list],
				})
				if (id) {
					getView(id)
				}
			}
		})
	}

	// 根据路由判断当前页面状态
	useEffect(() => {
		nodeList()
		if (id) {
			setStandbyId(() => id)
		}
		const hrefs = window.location.href
		if (hrefs.includes('view')) {
			setType('view')
		} else if (hrefs.includes('add')) {
			setOtherData({userId: props?.user?.userId})
			form.setFieldsValue({createName: props?.user?.userName})
			setType('add')
		} else {
			setType('edit')
		}
	}, [])

	// 保存
	const onSubmit = async () => {
		const formData = await form.validateFields()
		const len = stepsList?.filter((item: any) => item?.nodeTurn === 0)
		if (len?.length < 3) {
			message.warning('流程设置至少三个节点！')
		} else if (standbyId) {
			editStandby({
				id: standbyId,
				...formData,
				...otherData,
				nodeList: stepsList,
			})
				.then((res) => {
					if (res.success) {
						message.success(res.msg)
						history.goBack()
					}
				})
				.catch((err) => {
					message.error(err)
				})
		} else {
			addStandby({
				...formData,
				...otherData,
				nodeList: stepsList,
			})
				.then((res) => {
					if (res.success) {
						message.success(res.msg)
						history.goBack()
					}
				})
				.catch((err) => {
					message.error(err)
				})
		}
	}

	// 公司变化
	const onCompanyListChange = (value: string, option: any) => {
		setOtherData({...otherData, companyName: option[0]})
	}
	// 城市变化
	const onCitysChange = (value: any, selectedOptions: any) => {
		if (value) {
			setOtherData({
				...otherData,
				parentCityId: selectedOptions[0].id,
				cityId: selectedOptions[1].id,
				cityName: selectedOptions[1].name,
			})
		}
	}

	return (
		<div className={styles.admittanceAdd}>
			<div className={`${styles.content} ${styles.formDetils}`}>
				<Collapse
					defaultActiveKey={['1', '2']}
					ghost
					expandIconPosition="end">
					<Panel header={customizeHeader('基础信息')} key="1">
						<Form
							form={form}
							name="basic"
							layout="horizontal"
							labelCol={{flex: '120px'}}
							labelAlign="right"
							labelWrap
							initialValues={{remember: true}}
							autoComplete="off"
							disabled={type === 'view'}>
							<Row gutter={12}>
								<Col
									sm={{span: 24}}
									md={{span: 12}}
									lg={{span: 8}}>
									<Form.Item
										label="备车流程名称"
										name="processName"
										rules={[
											{required: true, message: '请输入'},
										]}>
										<Input
											placeholder="请输入"
											maxLength={60}
										/>
									</Form.Item>
								</Col>
								<Col span={24} />
								<Col
									sm={{span: 24}}
									md={{span: 12}}
									lg={{span: 8}}>
									<Form.Item
										label="所属公司"
										name="orgId"
										rules={[
											{required: true, message: '请选择'},
										]}>
										<TreeSelect
											showSearch
											style={{width: '100%'}}
											dropdownStyle={{
												maxHeight: 400,
												overflow: 'auto',
											}}
											placeholder="请选择"
											allowClear
											treeDefaultExpandAll
											fieldNames={{
												label: 'name',
												value: 'id',
											}}
											treeDataSimpleMode
											treeData={[...orgSource]}
											onChange={onCompanyListChange}
										/>
									</Form.Item>
								</Col>
								<Col
									sm={{span: 24}}
									md={{span: 12}}
									lg={{span: 8}}>
									<Form.Item
										label="所属城市"
										name="city"
										rules={[
											{required: true, message: '请选择'},
										]}>
										<Cascader
											fieldNames={{
												label: 'name',
												value: 'id',
												children: 'cityInfoList',
											}}
											options={citysList}
											placeholder="请选择"
											onChange={onCitysChange}
										/>
									</Form.Item>
								</Col>
								<Col
									sm={{span: 24}}
									md={{span: 12}}
									lg={{span: 8}}>
									<Form.Item
										label="创建人"
										name="createName"
										rules={[
											{required: true, message: '请输入'},
										]}>
										<Input placeholder="请输入" disabled />
									</Form.Item>
								</Col>
								<Col
									sm={{span: 24}}
									md={{span: 12}}
									lg={{span: 8}}>
									<Form.Item
										label="流程说明"
										name="processExplain"
										rules={[
											{required: true, message: '请输入'},
										]}>
										<TextArea
											maxLength={200}
											placeholder="请输入（最多200个字）"
											autoSize={{minRows: 2, maxRows: 3}}
										/>
									</Form.Item>
								</Col>
								<Col span={24}>
									<Form.Item
										label="流程设置"
										rules={[
											{required: true, message: '请选择'},
										]}
										name="nodeList">
										<Space>
											<div className="btn_ts">
												<InfoCircleOutlined />{' '}
												流程设置说明：
												蓝色代表流程开启，灰色代表流程关闭，黄色不可编辑，点击下方圆形框，可选择开启/关闭，操作完成后点击左上方保存，裸车档案完善流程则按照刚才设置的流程执行
											</div>
										</Space>
									</Form.Item>
								</Col>
							</Row>
						</Form>
						<Row gutter={12} className="steps">
							<Col span={24}>
								{stepsList.length > 0 ? (
									<Steps
										labelPlacement="vertical"
										onChange={onStepsChange}>
										{stepsList?.map(
											(
												item: {
													nodeName: string
													nodeTurn?: number
													nodeSort?: number
													nodeId: number
												},
												index: number,
											) => {
												if (
													index === 0 ||
													index ===
														stepsList.length - 1
												) {
													return (
														<>
															<Step
																title={
																	item.nodeName
																}
																disabled
																className="active1"
															/>
														</>
													)
												}
												if (item.nodeTurn === 1) {
													return (
														<>
															<Step
																title={
																	item.nodeName
																}
																className="active2"
																disabled={
																	type ===
																	'view'
																}
															/>
														</>
													)
												}
												return (
													<>
														<Step
															title={
																item.nodeName
															}
															className="active1"
															disabled={
																type === 'view'
															}
														/>
													</>
												)
											},
										)}
									</Steps>
								) : null}
							</Col>
						</Row>
					</Panel>
					{type === 'view' ? (
						<Panel
							header={customizeHeader('操作记录')}
							key="2"
							forceRender>
							<OperationRecord
								businessId={id}
								businessType={21}
							/>
						</Panel>
					) : (
						''
					)}
				</Collapse>
				<div className={styles.wrap}>
					<Button
						onClick={() => {
							history.go(-1)
						}}>
						取消
					</Button>
					{type === 'add' || type === 'edit' ? (
						<>
							<Button
								type="primary"
								htmlType="submit"
								onClick={onSubmit}>
								保存
							</Button>
						</>
					) : (
						''
					)}
				</div>
			</div>
		</div>
	)
})
export default connect(({user}: any) => ({user}))(standbyAdd)
